﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using VemTransporte.Models.Basica;
using System.Security.Cryptography;
using VemTransporte.Models.Persistencia;
using System.Data.Linq;

namespace VemTransporte.Models.Negocio
{
    public class ControladorTotal
    {
        private RepUsuario rUsuario;
        private RepEndereco rEndereco;
        private RepEmpresa rEmpresa;
        private RepTipoTelefone rTipoTelefone;
        private RepEmpresaTelefone rEmpresaTelefone;

        public ControladorTotal()
        {
            rUsuario = new RepUsuario();
            rEndereco = new RepEndereco();
            rEmpresa = new RepEmpresa();
            rTipoTelefone = new RepTipoTelefone();
            rEmpresaTelefone = new RepEmpresaTelefone();
        }

        #region Usuario
        public void Salvar(Usuario u)
        {

            if (rUsuario.ProcurarUsuarioPorEMail(u.Email) != null)
            {
                throw new Exception("O E-Mail já existe!");
            }

            u.Senha = EncryptString(u.Senha, "VemTransporteSecurity");

            if ((u.Endereco != null) && (u.Endereco.Id != 0))
            {
                //Usuário cadastrou um endereço
                Salvar(u.Endereco);
            }
            else
            {
                //Usuário ainda não possui endereço, apenas salvará o usuário
                rUsuario.Salvar(u);
            }
        }

        public void Remover(Usuario u)
        {
            rUsuario.Remover(u);
        }

        //Teste
        public Usuario ProcurarUsuarioPorId(int id)
        {
            return rUsuario.ProcurarPorId(id);
        }

        public Usuario ProcurarUsuarioPorEMail(string email)
        {
            return rUsuario.ProcurarUsuarioPorEMail(email);
        }

        public Usuario ProcurarUsuarioPorEmailESenha(string email, string senha)
        {
            Usuario u = rUsuario.ProcurarUsuarioPorEmailESenha(email, EncryptString(senha, "VemTransporteSecurity"));
            u.Senha = DecryptString(u.Senha, "VemTransporteSecurity");
            return u;
        }
        #endregion

        #region CEP

        public void Salvar(Endereco e)
        {
            rEndereco.Salvar(e);
        }

        public Endereco ProcurarEnderecoPorCep(string cep)
        {
            return rEndereco.ProcurarEnderecoPorCep(cep);
        }
        #endregion

        #region Empresa
        public void Salvar(Empresa e)
        {
            if (rEmpresa.ProcurarEmpresaPorEMail(e.Email) != null)
            {
                throw new Exception("O E-Mail já existe!");
            }
            rEmpresa.Context.SubmitChanges();
            //rEmpresa.Salvar(e);
        }

        public List<TipoTelefone> ProcurarTipoTelefoneTodos()
        {
            return rTipoTelefone.SelectAll();
        }
        #endregion

        #region Utils
        public static string EncryptString(string Message, string Passphrase)
        {
            byte[] Results;
            System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();

            // Step 1. We hash the passphrase using MD5
            // We use the MD5 hash generator as the result is a 128 bit byte array
            // which is a valid length for the TripleDES encoder we use below

            MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
            byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase));

            // Step 2. Create a new TripleDESCryptoServiceProvider object
            TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();

            // Step 3. Setup the encoder
            TDESAlgorithm.Key = TDESKey;
            TDESAlgorithm.Mode = CipherMode.ECB;
            TDESAlgorithm.Padding = PaddingMode.PKCS7;

            // Step 4. Convert the input string to a byte[]
            byte[] DataToEncrypt = UTF8.GetBytes(Message);

            // Step 5. Attempt to encrypt the string
            try
            {
                ICryptoTransform Encryptor = TDESAlgorithm.CreateEncryptor();
                Results = Encryptor.TransformFinalBlock(DataToEncrypt, 0, DataToEncrypt.Length);
            }
            finally
            {
                // Clear the TripleDes and Hashprovider services of any sensitive information
                TDESAlgorithm.Clear();
                HashProvider.Clear();
            }

            // Step 6. Return the encrypted string as a base64 encoded string
            return Convert.ToBase64String(Results);
        }

        public static string DecryptString(string Message, string Passphrase)
        {
            byte[] Results;
            System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();

            // Step 1. We hash the passphrase using MD5
            // We use the MD5 hash generator as the result is a 128 bit byte array
            // which is a valid length for the TripleDES encoder we use below

            MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
            byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase));

            // Step 2. Create a new TripleDESCryptoServiceProvider object
            TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();

            // Step 3. Setup the decoder
            TDESAlgorithm.Key = TDESKey;
            TDESAlgorithm.Mode = CipherMode.ECB;
            TDESAlgorithm.Padding = PaddingMode.PKCS7;

            // Step 4. Convert the input string to a byte[]
            byte[] DataToDecrypt = Convert.FromBase64String(Message);

            // Step 5. Attempt to decrypt the string
            try
            {
                ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor();
                Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length);
            }
            finally
            {
                // Clear the TripleDes and Hashprovider services of any sensitive information
                TDESAlgorithm.Clear();
                HashProvider.Clear();
            }

            // Step 6. Return the decrypted string in UTF8 format
            return UTF8.GetString(Results);
        }
    #endregion
    }
}